<template>
    <!-- 商家信息 -->
    <van-row style="padding-top:10px;padding-bottom:10px;background-color: beige;box-sizing: border-box;">
        <van-col span="8" offset="2">
            <img :src="business.businessImg" style="width: 100%;"/>
        </van-col>
        <van-col span="12" offset="2">
            <div>商家名称：{{business.businessName}}</div>
            <div>商家简介：{{business.businessExplain}}</div>
            <div>商家地址：{{business.businessAddress}}</div>
            <van-row>
              <van-col span="10" offset="14" align="center">
                <!-- 购物车图标  在图标库网站里复制即可 -->
                <svg @click="showCart" style="margin-top: 10px;" 
                t="1732848317898" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="35556" width="32" height="32"><path d="M1013.318 283.028c-5.165-7.135-13.437-11.373-22.256-11.373h-764.063l-52.463-219.533c-2.956-12.366-14.006-21.082-26.714-21.082h-115.701c-15.168 0-27.465 12.285-27.465 27.465 0 15.182 12.295 27.465 27.465 27.465h94.028l168.638 705.673c-41.965 12.96-72.751 51.654-72.751 97.817 0 56.727 46.141 102.86 102.845 102.86 56.714 0 102.854-46.133 102.854-102.86 0-17.387-4.749-33.531-12.397-47.903h244.8c-7.65 14.373-12.397 30.516-12.397 47.903 0 56.727 46.141 102.86 102.854 102.86 56.707 0 102.845-46.133 102.845-102.86 0-56.701-46.141-102.833-102.845-102.833h-400.531l-12.252-51.257h518.265c11.847 0 22.362-7.591 26.077-18.857l134.986-408.785c2.769-8.369 1.347-17.569-3.822-24.703zM750.595 841.557c26.419 0 47.917 21.484 47.917 47.903s-21.498 47.93-47.917 47.93c-26.426 0-47.922-21.51-47.922-47.93-0.001-26.419 21.497-47.903 47.922-47.903zM372.809 889.461c0 26.419-21.498 47.93-47.922 47.93-26.419 0-47.917-21.51-47.917-47.93 0-26.419 21.498-47.903 47.917-47.903 26.426 0 47.922 21.484 47.922 47.903z" fill="#d81e06" p-id="35557"></path></svg>
              </van-col>
            </van-row>
        </van-col>
    </van-row>
    <!-- -------------------- -->
    <van-row style="margin-top: 10px;">
    <van-col span="24">
      <!-- 查询餐品信息 -->
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="getFoodByBid"
          >
            <!-- 列表项 -->
            <van-row style="margin-top: 5px"  v-for="food in foodList" :key="food.foodId">
              <van-col :span="8" align="center" >
                  <img :src="food.foodImg" style="width: 60%;height: 60px;">
              </van-col>
              <van-col :span="13" align="left" >
                  <div style="font-size: 16px;">{{food.foodName}}</div>
                  <div style="font-size: 12px;">￥{{food.foodPrice}}</div>
                  <div style="font-size: 12px;">{{food.foodExplain}}</div>
              </van-col>
              <van-col :span="3" align="center" style="margin-top: 40px;">
                <!-- 点击该图标可以将餐品加入购物车 
                    foodId(需要通过点击的图标获取到所在行的餐品id)
                    businessId(从商家页面跳转过来时传递的)
                    userId(用户登录之后可以从本地存储来获取)
                -->
                <svg @click="addToCart(food.foodId)"  t="1732846529248" class="cartIcon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="31196" width="16" height="16"><path d="M962.079334 545.28l61.44-352.768c1.536-7.68-0.512-14.848-5.632-20.992-5.12-5.632-12.288-9.216-19.456-9.216H279.583334c-14.336 0-25.6 11.264-25.6 25.6s11.264 25.6 25.6 25.6h688.64l-53.248 304.128-631.296 84.48L184.351334 137.728c-1.536-7.68-6.656-14.336-13.824-17.408l-133.632-66.56c-12.8-6.144-28.16-1.024-34.304 11.776-6.144 12.8-1.024 28.16 11.776 34.304l122.368 60.416L266.271334 765.44c2.56 11.776 12.8 20.48 25.088 20.48h663.552c14.336 0 25.6-11.264 25.6-25.6s-11.264-25.6-25.6-25.6H311.839334l-17.408-81.92 645.632-86.016c11.264-2.048 19.968-10.752 22.016-21.504z" fill="#d81e06" p-id="31197"></path><path d="M395.295334 896m-51.2 0a51.2 51.2 0 1 0 102.4 0 51.2 51.2 0 1 0-102.4 0Z" fill="#d81e06" p-id="31198"></path><path d="M866.335334 896m-51.2 0a51.2 51.2 0 1 0 102.4 0 51.2 51.2 0 1 0-102.4 0Z" fill="#d81e06" p-id="31199"></path></svg>
              </van-col>
            </van-row>
        </van-list>
    </van-col>
  </van-row>
   <!-- 底部弹出 -->
   <van-popup
    v-model:show="showPopCart"
    position="bottom"
    :style="{ height: '70%' }"
    closeable
    close-icon="close"
    >
    <div>购物车</div>
    <van-card
        v-for="cartItem in cartList"
        :key="cartItem.cartId"
        :num="cartItem.quantity"
        :price="cartItem.food.foodPrice"
        :desc="cartItem.food.foodExplain"
        :title="cartItem.food.foodName"
        :thumb="cartItem.food.foodImg"
    >
    <!-- <template #tags>
        <van-tag plain type="primary">标签</van-tag>
        <van-tag plain type="primary">标签</van-tag>
    </template> -->
    <template #footer>
        <van-button size="mini" @click="decrease(cartItem)">-</van-button>
        <van-button size="mini" @click="add(cartItem)">+</van-button>
    </template>
    </van-card>

    <van-submit-bar :price="allPrice*100" button-text="提交订单" @submit="addOrder">
        <template #tip>
            <span v-if="chosenAddress">
                {{chosenAddress.contactName}}|{{chosenAddress.contactTel}}|{{chosenAddress.address}},
            </span>
            <span v-else>
                请选择收货地址, 
            </span>
            <span @click="showAddress">查看地址</span>
        </template>
    </van-submit-bar>
  
  </van-popup>

  <!-- 显示地址 -->
  <van-popup
    v-model:show="showPopAddress"
    position="bottom"
    :style="{ height: '70%' }"
    closeable
    close-icon="close"
    >
  </van-popup>
</template>
<script setup>
// 当我们来到商家界面的时候，一边显示商家的信息，然后另一边显示，该商家下面的餐品信息，然后商家和餐品傍边都有一个购物车
//当点击上面购物车的时候，显示的是购物车信息，也就是订单详情，点击下面购物车的话，显示的是加入该购物车
import { showNotify } from 'vant';
import { onMounted,getCurrentInstance,ref, computed } from 'vue';
import {Popup} from 'vant';
import store from '@/store';

        const {proxy} = getCurrentInstance();
        const loading = ref(false);  //加载的状态  查询之前置为true  查询完毕置为false
        const finished = ref(false);  //所有的数据全部查完之后置为true

        const bid = ref(null);  //商家id值
        const foodList =ref([]);
        //开始发送请求
        // 获取该商家下的餐品信息
        const getFoodByBid =()=>{
            if(bid.value==null) {
                showNotify({message:'该商家编号为空，无法进行查询'});
            }
            loading.value = true;

            proxy.$axios({
                method:'get',
                url:'/food/business/'+bid.value
            }).then(res=>{
                let resultBean=res.data;
                if(resultBean.code==200) {
                    foodList.value=resultBean.data;
                    finished.value=true;
                    loading.value = false;
                } else {
                    showNotify({message:resultBean.msg});
                }
            }).catch(error=>{
                showNotify({message:error.message});
            })
        }
        //查询该商家信息
        let business=ref({});
        const getBusinessById=()=>{
            proxy.$axios({
                method:'get',
                url:'/business/'+bid.value
            }).then(res=>{
                let resultBean=res.data;
                if(resultBean.code==200) {
                    business.value=resultBean.data;
                } else {
                    showNotify({message:resultBean.msg});
                }
            }).catch(error=>{
                showNotify({message:error.message});
            })
        }
        //这里不是添加购物车项直接发送参数就行了
        //默认的用户是1号用户
        const cartList = ref([]);
        //弹出层是否显示
        const showPopCart = ref(false);
        //这是再点击上面的那个大图标所触发的事件
        const showCart=()=>{
            proxy.$axios({
                method:'get',
                url:'/cart/1/'+bid.value
            }).then(res=>{
                let resultBean=res.data;
                if(resultBean.code==200) {
                    cartList.value=resultBean.data;
                    showPopCart.value=true;
                } else {
                    showNotify({message:resultBean.msg});
                }
            }).catch(error=>{
                    showNotify({message:error.message});
            })
            getAddressById();
        }
        //写选中的地址
        const chosenAddress=ref(null);
        
        const getAddressById=()=>{
            if(store.state.chosenAddressId){
                proxy.$axios({
                    method: 'get',
                    url: '/address/'+store.state.chosenAddressId
                }).then(res=>{
                    let resultBean = res.data;
                    if(resultBean.code == 200){
                        chosenAddress.value =  resultBean.data;
                        console.log(chosenAddress.value);
                    }
                })
            }
        }
        //在点击餐品的图标的时候，直接添加到购物车里面，
        //先进行构造参数
         const user=ref(null);

        const addToCart=(foodId)=>{
            let userJson = window.localStorage.getItem("loginUser");
            if(userJson==null) {
                showNotify({message:'请先登录'})
                proxy.$router.push('/login');
                return;
            }
            //进行赋值
            user.value = JSON.parse(userJson);

            let cartItem={
                foodId:foodId,
                userId:user.value.userId,
                businessId:bid.value,
                quantity:1
            }
            proxy.$axios({
                method:'post',
                url:'/cart/save',
                data:cartItem
            }).then(res=>{
                let resultBean=res.data;
                if(resultBean.code==200) {
                    showNotify({message:'添加餐品成功'})
                } else {
                    showNotify({message:resultBean.msg});
                }
            }).catch(error=>{
                showNotify({message:error.message})
            })
        }
        //减少购物车上的餐品数量
        const decrease=(cartItem)=>{
            //先直接进行减的操作
            //1.减完之后在进行判断，如果减为零的话，直接将这个购物车删除
            //2.不为零的话，修改数据quantity的值
            //直接开始操作，不打印
            cartItem.quantity-=1;
            console.log('decrease',cartItem);
            if(cartItem.quantity==0) {
                proxy.$axios({
                    method:'delete',
                    url:'/cartItem/'+cartItem.cartId
                }).then(res=>{
                    let resultBean=res.data;
                    if(resultBean.code==200) {
                        showNotify({message:'删除餐品成功'});
                        //删除成功之后还要进行重新查询
                        showCart();
                    } else {
                        showNotify({message:resultBean.msg});
                        //删除失败的话，还要还原原来的餐品数量
                        cartItem.quantity+=1;
                    }
                }).catch(error=>{
                    showNotify({message:error.message});
                })
                return ;
            }
            //程序走到 这里的话，相当于进行修改餐品的数量
            //发卡修改的操作
            proxy.$axios({
                method:'post',
                url:'/cart/save',
                data:cartItem
            }).then(res=>{
                let resultBean=res.data;
                if(resultBean.code==200) {
                       showNotify({message:'减少餐品数量成功'})
                } else {
                        showNotify({message:resultBean.msg});
                        //删除失败的话，还要还原原来的餐品数量
                        cartItem.quantity+=1;
                    }
                }).catch(error=>{
                    showNotify({message:error.message});
            })
        }
        const add=(cartItem)=>{
            cartItem.quantity+=1;
            console.log('add',cartItem);
            proxy.$axios({
                method:'post',
                url:'/cart/save',
                data:cartItem
            }).then(res=>{
                let resultBean=res.data;
                if(resultBean.code==200) {
                       showNotify({message:'增加餐品数量成功'})
                    } else {
                        showNotify({message:resultBean.msg});
                        //删除失败的话，还要还原原来的餐品数量
                        cartItem.quantity-=1;
                    }
                }).catch(error=>{
                    showNotify({message:error.message});
            })
        }
        const allPrice=computed(()=>{
            let sum=0;
            cartList.value.forEach((cartItem)=>{
                sum+=cartItem.food.foodPrice*cartItem.quantity;
            })
            return sum;
        })
        //这里发现一个bug，当购物车里没有餐品的时候 ，这时候弹出的对话层也要直接显示没了
        //下订单
        const addOrder = ()=>{

            let userJson = window.localStorage.getItem("loginUser");
            if(userJson==null) {
                showNotify({message:'请先登录'})
                proxy.$router.push('/login');
                return;
            }
            //进行赋值
            user.value = JSON.parse(userJson);

            let orderDetailList =[];
            cartList.value.forEach((cartItem)=>{
                orderDetailList.push({
                    foodId:cartItem.foodId,
                    quantity:cartItem.quantity
                })
            })
            let order={
                userId: user.value.userId,
                businessId: bid.value,
                addressId: store.state.chosenAddressId,
                orderTotal: allPrice.value,
                detailList: orderDetailList
            }
            proxy.$axios({
                method:'post',
                url:'/order/add',
                data:order
            }).then(res=>{
                let resultBean=res.data;
                if(resultBean.code==200) {
                    //再提交成功订单的时候，购物车要进行清空，然后弹出层消失
                    showNotify({message:'下单成功'})
                    cartList.value=[];
                    showPopCart.value=false;
                } else {
                    showNotify({message:resultBean.msg});
                }
            }).catch(error=>{
                showNotify({message:error.message});
            })
        }
        //展示地址
        const showAddress = ()=>{
            proxy.$router.push('/main/address');
        }
        onMounted(()=>{
            //这里$route表示的是当前这个路由，路由传递参数
            console.log('该商家的编号为:'+proxy.$route.params.bid);
            bid.value=proxy.$route.params.bid;
            getBusinessById();
        })
</script>
<style scoped>

</style>
